package com.tenglong.teacher.ui.publish;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.DensityUtil;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.google.gson.Gson;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.requestInfo.CorrectInfo;
import com.tenglong.teacher.data.requestInfo.WorkPaperMistakesInfo;
import com.tenglong.teacher.data.resultInfo.DictByType;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.adapter.WorkPaperAdapter;
import com.tenglong.teacher.ui.common.activity.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WorkPaperActivity extends BaseActivity {
    public static final String KEY_IMAGE_INFO_LIST = "key_image_info_list";

    private RecyclerView recyclerView;
    private TextView writingScore;
    private ViewGroup writingScoreOption;
    private TextView teacherReviews;
    private ViewGroup teacherReviewsOption;
    private EditText commentEit;

    /**
     * 发布作业（计数参数）
     */
    private int succeedSendImageNum = 0;

    private List<WorkPaperMistakesInfo> infos;
    private WorkPaperAdapter mAdapter;
    private List<String> writingTexts;
    private List<String> teacherReviewsTexts;

    private String writingScoreText;
    private String teacherReviewsText;
    private String sessionId;
    private String studentId;
    private List<CorrectInfo> imageInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workpaper);
        imageInfo = (List<CorrectInfo>) getIntent().getSerializableExtra(KEY_IMAGE_INFO_LIST);
        CorrectInfo info = imageInfo.get(0);
        sessionId = info.sessionId;
        studentId = info.studentAccId;
        infos = new ArrayList<>();
        List<List<String>> list = new ArrayList<>();
        for (CorrectInfo correctInfo : imageInfo) {
            for (List<String> str : correctInfo.erreList) {
                list.add(str);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            WorkPaperMistakesInfo mistakesInfo = new WorkPaperMistakesInfo();
            mistakesInfo.index = i + 1;
            mistakesInfo.errorCause = list.get(i);
            infos.add(mistakesInfo);
        }
        initView();
        initRecy();
        setAdapter();
        setListeners();
    }

    private void setListeners() {
        for (int i = 0; i < writingScoreOption.getChildCount(); i++) {
            writingScoreOption.getChildAt(i).setOnClickListener(this);
        }
        for (int i = 0; i < teacherReviewsOption.getChildCount(); i++) {
            teacherReviewsOption.getChildAt(i).setOnClickListener(this);
        }
        commentEit.setOnClickListener(this);
        findViewById(R.id.sendReform).setOnClickListener(this);
        findViewById(R.id.sendComplete).setOnClickListener(this);
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams();
                if (Build.VERSION.SDK_INT >= 16) {
                    recyclerView.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    recyclerView.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
                int height = DensityUtil.dp2px((float) 110.8);
                if (recyclerView.getHeight() > height) {
                    layoutParams.height = height;
                }
                recyclerView.setLayoutParams(layoutParams);
            }
        });
    }

    private void setAdapter() {
        mAdapter = new WorkPaperAdapter(infos);
        recyclerView.setAdapter(mAdapter);
    }

    private void initRecy() {
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int dp = Utils.dip2px(parent.getContext(), (float) 10);
                outRect.left = 0;
                outRect.right = 0;
                outRect.bottom = dp;
                outRect.top = dp;
            }
        });
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    }

    private void initView() {
        setTitle("作业报告");
        recyclerView = findViewById(R.id.recyclerView);
        writingScore = findViewById(R.id.writingScore);
        writingScoreOption = findViewById(R.id.writingScoreOption);
        teacherReviews = findViewById(R.id.teacherReviews);
        teacherReviewsOption = findViewById(R.id.teacherReviewsOption);
        commentEit = findViewById(R.id.commentEit);
        ((View) recyclerView.getParent()).setVisibility(infos.size() == 0 ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.writingScoreA:
            case R.id.writingScoreB:
            case R.id.writingScoreC:
            case R.id.writingScoreD:
                if (writingTexts != null && writingTexts.size() > 0) {
                    writingScore(v);
                } else {
                    getWritingScoreList("font_level", v);
                }
                break;
            case R.id.teacherReviewsOptionA:
            case R.id.teacherReviewsOptionB:
            case R.id.teacherReviewsOptionC:
            case R.id.teacherReviewsOptionD:
                if (teacherReviewsTexts != null && teacherReviewsTexts.size() > 0) {
                    teacherReview(v);
                } else {
                    getWritingScoreList("hw_level", v);
                }
                break;
            case R.id.sendReform:
                if (infos == null || infos.size() == 0) {
                    ToastUtils.showCenterToast("没有错误，不能发回改错");
                    return;
                }
                if (TextUtils.isEmpty(writingScoreText)) {
                    ToastUtils.showCenterToast("请给该学生字迹评分");
                    return;
                }
                if (TextUtils.isEmpty(teacherReviewsText)) {
                    ToastUtils.showCenterToast("请给该学生点评");
                    return;
                }
                publishHomework("1");
                break;
            case R.id.sendComplete:
                if (TextUtils.isEmpty(writingScoreText)) {
                    ToastUtils.showCenterToast("请给该学生字迹评分");
                    return;
                }
                if (TextUtils.isEmpty(teacherReviewsText)) {
                    ToastUtils.showCenterToast("请给该学生点评");
                    return;
                }
                publishHomework("0");
                break;
        }
    }

    private void publishHomework(final String type) {
        showProgressDialog("正在上传批改中(" + (succeedSendImageNum + 1) + "/" + imageInfo.size() + ")");
        for (int i = 0; i < imageInfo.size(); i++) {
            final CorrectInfo info = imageInfo.get(i);
            RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), info.filename);
            RequestBody sessionId = RequestBody.create(MediaType.parse("text/plain"), info.sessionId);
            RequestBody errors = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(info.erreList));
            RequestBody studentAccId = RequestBody.create(MediaType.parse("text/plain"), info.studentAccId);
            RequestBody imMsgId = RequestBody.create(MediaType.parse("text/plain"), info.imMsgId);
            File file = new File(info.scrawlPath);
            RequestBody photoBody =
                    RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part photoPart = MultipartBody.Part.createFormData("pngimg", file.getName(), photoBody);
            CreateRequestEntity.getWebService().homeworkCorrectupload(photoPart, filename, sessionId,
                    errors, studentAccId, imMsgId).enqueue(new Callback<BaseResult<Boolean>>() {
                @Override
                public void onResponse(Call<BaseResult<Boolean>> call, Response<BaseResult<Boolean>> response) {
                    if (ResultVerifier.isSucceed(response)) {
                        if (response.body().data) {
                        }
                    } else {
                        ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                    }
                    statisticsNum(this, type);
                }

                @Override
                public void onFailure(Call<BaseResult<Boolean>> call, Throwable t) {
                    ResultVerifier.systerErrers(t);
                    statisticsNum(this, type);
                }
            });
        }
    }

    /**
     * 发布作业统计图片方法
     * @param callback
     */
    private void statisticsNum(Callback<BaseResult<Boolean>> callback, String type) {
        synchronized (callback) {
            succeedSendImageNum += 1;
            setProgressDialogMessage("正在上传批改(" + (succeedSendImageNum + 1) + "/" + imageInfo.size() + ")");
            if (succeedSendImageNum == imageInfo.size()) {
                succeedSendImageNum = 0;
                uploadData(type);
            }
        }
    }

    private synchronized void uploadData(final String type) {
        setProgressDialogMessage("正在上传...");
        RequestBody seId = RequestBody.create(MediaType.parse("text/plain"), sessionId);
        RequestBody stuId = RequestBody.create(MediaType.parse("text/plain"), studentId);
        RequestBody teacherText = RequestBody.create(MediaType.parse("text/plain"), teacherReviewsText);
        RequestBody writingText = RequestBody.create(MediaType.parse("text/plain"), writingScoreText);
        RequestBody comments = RequestBody.create(MediaType.parse("text/plain"), commentEit.getText().toString().trim());
        RequestBody typeParam = RequestBody.create(MediaType.parse("text/plain"), type);
        CreateRequestEntity.getWebService().homeworkCorrectComplete(seId, stuId, writingText, teacherText, comments, typeParam).enqueue(new Callback<BaseResult<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResult<Boolean>> call, Response<BaseResult<Boolean>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    if (response.body().data) {
                        ToastUtils.showCenterToast("批改完成");
                        Intent data = new Intent();
                        data.putExtra(GlobalConstant.RESULT_CODE_CORRECT_HOMEWORK, type.equals("1") ? 4 : 2);
                        setResult(Activity.RESULT_OK, data);
                        finish();
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<Boolean>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                dismissProgressDialog();
            }
        });
    }

    private void writingScore(View v) {
        writingScoreText = writingTexts.get(writingScoreOption.indexOfChild(v));
        setWritingScoreOptionState(v);
        setCommit((TextView) ((ViewGroup) v).getChildAt(0), "卷面字迹评分：", writingScoreText, writingScore);
    }

    private void teacherReview(View v) {
        teacherReviewsText = teacherReviewsTexts.get(teacherReviewsOption.indexOfChild(v));
        setTeacherReviewsOptionState(v);
        setCommit((TextView) ((ViewGroup) v).getChildAt(0), "老师点评：", teacherReviewsText, teacherReviews);
    }

    private void getWritingScoreList(final String type, final View v) {
        showProgressDialog("数据获取中...");
        CreateRequestEntity.getWebService().getDictByType(type).enqueue(new Callback<BaseResult<List<DictByType>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<DictByType>>> call, Response<BaseResult<List<DictByType>>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    if (response.body().data.size() >= 4) {
                        if (type.equals("font_level")) {
                            writingTexts = new ArrayList<>();
                            for (DictByType dictByType : response.body().data) {
                                writingTexts.add(dictByType.label);
                            }
                            writingScore(v);
                        } else {
                            teacherReviewsTexts = new ArrayList<>();
                            for (DictByType dictByType : response.body().data) {
                                teacherReviewsTexts.add(dictByType.label);
                            }
                            teacherReview(v);
                        }
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<List<DictByType>>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }


    private void setCommit(TextView v, String s, String writingScoreText, TextView writingScore) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(s);
        stringBuilder.append(v.getText().toString().trim());
        stringBuilder.append(" ");
        stringBuilder.append(writingScoreText);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder.toString());
        spannableStringBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.app_red)), s.length(), stringBuilder.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        writingScore.setText(spannableStringBuilder);
    }

    private void setWritingScoreOptionState(View v) {
        for (int i = 0; i < writingScoreOption.getChildCount(); i++) {
            View childView = ((ViewGroup) writingScoreOption.getChildAt(i)).getChildAt(0);
            childView.setSelected(v == writingScoreOption.getChildAt(i));
        }
    }

    private void setTeacherReviewsOptionState(View v) {
        for (int i = 0; i < teacherReviewsOption.getChildCount(); i++) {
            View childView = ((ViewGroup) teacherReviewsOption.getChildAt(i)).getChildAt(0);
            childView.setSelected(v == teacherReviewsOption.getChildAt(i));
        }
    }
}
